package com.example.tableapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.os.StrictMode;
import android.text.Editable;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import com.example.tableapplication.application.MyApplication;
import com.example.tableapplication.dao.SOAPUtil;
import com.google.gson.JsonObject;

public class MainActivity extends AppCompatActivity  {

    MyApplication myApplication;
    private Button login_btn;       //登录按钮
    private Button scan_setting;    //扫描设置按钮
    private Button data_source;     //数据源配置按钮
    private CheckBox checkBox2;     //是否保存按钮
    private EditText editText1;     //服务器输入框
    private EditText editText2;     //用户名输入框
    private EditText editText3;     //密码输入框
    private static boolean registeOpenCount = false;  //记录是否计算过输入框位置，不重复计算
    private int name_etleft, name_ettop, name_et_bottom, name_et_right;
    private int passWord_etleft, passWord_ettop, passWord_et_bottom, passWord_et_right;


    /**
     * 点击空白处关闭输入法-------主方法。
     * @param
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (!registeOpenCount) {
            calculateEtXY();
            registeOpenCount = true;
        }
        if (ev.getAction() == MotionEvent.ACTION_DOWN){
            return super.dispatchTouchEvent(ev);
        }
        else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
            return super.dispatchTouchEvent(ev);
        }
        else if (ev.getAction() == MotionEvent.ACTION_UP) {
            boolean b = false;
            Context applicationContext = getApplicationContext();
            View v = getCurrentFocus();
            float x = ev.getX();
            float y = ev.getY();
            b = isAlsoET(x, y);
            if (!b) {//如果点击的位置不是输入框
                if (v instanceof EditText)
                    v.clearFocus();//如果当前获得焦点的是输入框EditText，就清除焦点
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    try {
                        //此处window有时获取为null,直接try..catch，
                        IBinder windowToken = v.getWindowToken();
                        imm.hideSoftInputFromWindow(windowToken, 0);
                    }catch (Exception e ){

                    }

                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);

    }
    //     点击空白处关闭输入法-------事先计算好所有EditText的x,y坐标，用到的时候不用重复计算
    public void calculateEtXY() {
        int[] name_etleftTop = { 0, 0 };
        editText2.getLocationInWindow(name_etleftTop);
        name_etleft = name_etleftTop[0];
        name_ettop = name_etleftTop[1];
        name_et_bottom = name_ettop + editText2.getHeight();
        name_et_right = name_etleft + editText2.getWidth();


        int[] passWord_etleftTop = { 0, 0 };
        editText3.getLocationInWindow(passWord_etleftTop);
        passWord_etleft = passWord_etleftTop[0];
        passWord_ettop =  passWord_etleftTop[1];
        passWord_et_bottom = passWord_ettop + editText3.getHeight();
        passWord_et_right = passWord_etleft + editText3.getWidth();
    }
    //      点击空白处关闭输入法-------判断点击的区域是否是文本框
    public boolean isAlsoET(float x, float y) {
        if ((x > name_etleft) && (y > name_ettop) && (x < name_et_right) && (y < name_et_bottom))
            return true;
        if ((x > passWord_etleft) && (y > passWord_ettop) && (x < passWord_et_right) && (y < passWord_et_bottom))
            return true;
        return false;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        myApplication= (MyApplication) getApplication();
        login_btn=(Button) findViewById(R.id.button1);
        scan_setting=(Button) findViewById(R.id.button2);
        data_source=(Button) findViewById(R.id.button3);
        checkBox2=(CheckBox)findViewById(R.id.checkBox2);
        editText1=(EditText)findViewById(R.id.editText1);
        editText2=(EditText)findViewById(R.id.editText2);
        editText3=(EditText)findViewById(R.id.editText3);
        if(myApplication.getDbsource_state()){
            if(myApplication.getEt_dbadress().equals("")||myApplication.getEt_dbport().equals("")){
                editText1.setText("");
            }else{
                editText1.setText(myApplication.getEt_dbadress()+":"+myApplication.getEt_dbport());
            }
        }
        if(myApplication.getLogin_state()){
            editText2.setText(myApplication.getLogin_username());
            editText3.setText(myApplication.getLogin_password());
        }
        if(myApplication.getSave_password()){
            checkBox2.setChecked(true);
        }


        //添加渲染完毕后的监听事件，页面加载完毕后，判断是否输入
//        final View view = (View) findViewById(R.id.linearLayout);
//        final  ViewTreeObserver.OnGlobalLayoutListener mOnGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
//
//            @Override
//            public void onGlobalLayout() {
//                //todu 这里写你要在界面加载完成后执行的操作。
//                System.out.println("页面加载完毕~~~~~！！！！");
//            }
//        };
//        view.getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener);




        //隐藏前台输入的密码
        editText3.setTransformationMethod(PasswordTransformationMethod.getInstance());
        //登录界面数据源信息不可编辑
        editText1.setFocusableInTouchMode(true);


//        //读取本地存储的信息
//        readManger();
//        //保存本地存储的信息
//        saveManger();

        //登录按钮事件监听
        login_btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
//                MainActivity_1.showDialog(MainActivity.this);
                if(checkBox2.isChecked()){
                    myApplication.setSave_password(true);
                }
                myApplication.setLogin_username(editText2.getText().toString());
                myApplication.setLogin_password(editText3.getText().toString());
                if(checkLogin()){
                    myApplication.saveManger();
                    Intent intent =new Intent("android.intent.action.MAIN_2");
                    startActivity(intent);
                }else{
                    MainActivity_1.showDialog(MainActivity.this,"检查用户名或者密码是否输入正确");
                }


            }
        });

        //扫描设置按钮事件监听
        scan_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =new Intent("android.intent.action.MAIN_1");
                startActivity(intent);
            }
        });
        //数据源配置按钮事件监听
        data_source.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
//                MainActivity_1.showDialog(MainActivity.this);
                Intent intent =new Intent("android.intent.action.MAIN_3");
                startActivity(intent);

            }
        });
    }






    /**
     *  保存用户名密码功能
     */
    public void saveManger(){
        //点击登录按钮， 保存输入框内容， 存储到 本地
        login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //获取 输入的服务器内容
                String inputService =  editText1.getText().toString();

                //获取 输入的用户名信息
                String  inputUsername =  editText2.getText().toString();

                //勾选了保存密码逻辑
                SharedPreferences spf = getSharedPreferences("info", MODE_PRIVATE);
                SharedPreferences.Editor editor = spf.edit();
                if(checkBox2.isChecked()) {
                    //获取 输入的密码信息
                    String inputPassword =  editText3.getText().toString();
                    editor.putString("password",inputPassword);
                }else{
                    //删除本地储存的密码
                    editor.remove("password");
                }
                if (inputService.isEmpty()||inputUsername.isEmpty() ){
                    //此处添加弹窗控件
                }else{
                    //保存页面信息到本地
                    editor.putString("service",inputService);
                    editor.putString("username",inputUsername);
                    editor.commit();
                }
                Intent intent = new Intent("android.intent.action.MAIN_2");
                startActivity(intent);
            }

        });
    }

    /**
     * 读取用户名密码功能
     */
    public void readManger(){
        //读取存储在本地的信息
        //创建SharedPreferences对象
        SharedPreferences sp = getSharedPreferences("info", MODE_PRIVATE);
        //获得保存在SharedPredPreferences中的用户名和密码
        String service = sp.getString("service", "");
        String userName = sp.getString("username", "");
        String passWord = sp.getString("password", "");
        //在用户名和密码的输入框中显示用户名和密码
        editText1.setText(userName);
        editText2.setText(passWord);
        editText3.setText(service);
    }

    /**
     * 校验用户名和密码功能
     */
    public boolean checkLogin(){
        //获取前台输入框用户名和密码
        String userName = editText2.getText().toString();
        String passWord = editText3.getText().toString();
        JsonObject json=new JsonObject();
        json.addProperty("login_username",userName);
        json.addProperty("login_password",passWord);
        //查询数据库
//        MainActivity_2 main2=new MainActivity_2();
//        StringBuilder str = new StringBuilder();
//        str.append("SELECT count(*) FROM AP_USER WEHRE NAME='");
//        str.append(userName+"' AND password ='");
//        str.append(passWord+"'");
          String res = connect("checkLogin",json);
        //解析connect，josn字符串，获取sql语句查询返回的结果
        //如果查询结果条数为0返回flase， 如果为1，返回true;
        if(res.equals("true")){
            return true;
        }
        return false;
    }
    public String connect(String method, JsonObject json){
        //服务器地址
        String dbip=myApplication.getEt_dbadress();
        String dbport=myApplication.getEt_dbport();
        String dbname=myApplication.getEt_dbname();
        String dbusername=myApplication.getEt_dbusername();
        String dbpassword=myApplication.getEt_dbpassword();
        String wsdUrl="http://"+dbip+":9090/ConnectToU8/services/TableInfoService?wsdl";
        //方法名
//        String method1=method;
//        HashMap param1=new HashMap();
//        param1.put("dbip",dbip);
//        param1.put("dbport",dbport);
//        param1.put("dbname",dbname);
//        param1.put("dbusername",dbusername);
//        param1.put("dbpassword",dbpassword);

//        JsonObject json =new JsonObject();
        json.addProperty("dbip",dbip);
        json.addProperty("dbport",dbport);
        json.addProperty("dbname",dbname);
        json.addProperty("dbusername",dbusername);
        json.addProperty("dbpassword",dbpassword);
        Object result= SOAPUtil.doTransport(wsdUrl, method,json.toString());
//        JSONArray jsonArray = null;
//        try {
//            jsonArray = new JSONArray(result.toString().trim());
//            if(jsonArray.length() > 0){
//                for (int i = 0; i < jsonArray.length(); i++) {
//                    JSONObject jsonObject = null;
//                    jsonObject = jsonArray.getJSONObject(i);
//                    System.out.println("遍历jsonArray,获取数组中的name属性值："+jsonObject.get("xingming"));
//                }
//            }
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
        return result.toString();
//        results.setText(result.toString());
    }

}